package com.zcdyy.rentalofhouse.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.youth.banner.loader.ImageLoaderInterface;
import com.zcdyy.rentalofhouse.R;
import com.zcdyy.rentalofhouse.application.MyApplication;
import com.zcdyy.rentalofhouse.bean.Account;
import com.zcdyy.rentalofhouse.bean.AllRental;
import com.zcdyy.rentalofhouse.bean.OrderInfo;
import com.zcdyy.rentalofhouse.constant.Constants;
import com.zcdyy.rentalofhouse.utils.BaseTranslucentActivity;
import com.zcdyy.rentalofhouse.utils.BmobUtils;
import com.zcdyy.rentalofhouse.utils.ImageLoaderUtils;
import com.zcdyy.rentalofhouse.utils.ImageUploadUtil;
import com.zcdyy.rentalofhouse.utils.ImageUtil;
import com.zcdyy.rentalofhouse.utils.ToastUtils;
import com.zcdyy.rentalofhouse.views.ActionSheet;
import com.zcdyy.rentalofhouse.views.CircleImageView;

import java.io.File;

import cn.bmob.v3.datatype.BmobFile;

public class WholeRentDetailsActivity extends BaseTranslucentActivity implements View.OnClickListener ,ActionSheet.OnSheetItemClickListener{

    private static int type = 0;//0表示整租，1表示二手房，2表示单间，3表示商铺
    //拍照、从相册选择、照片保存成功
    private final int TAKE_PHOTO = 1, CHOOSE_PHOTO = 2, SAVE_IMAGE_SUCCESS = 3;
    private final int REQUEST_CODE = 0;
    public AllRental allRental;
    public OrderInfo orderInfo;
    private TextView tvPublish;//发布按钮
    private TextView tvTitle;//标题栏
    private TextView tvMiaoShuChoose,tvPay;//描述   付款方式
    private RelativeLayout rlPayStyle;//付款方式的点击控件
    private RelativeLayout rlDesc;//描述点击控件
    private CircleImageView head;//用户上传的房屋图片
    private EditText xiaoqu;//小区
    private EditText address;//区域
    private EditText shi;//室
    private EditText ting;//厅
    private EditText wei;//卫
    private EditText mianji;//面积
    private EditText price;//租金
    private EditText biaoti;//标题
    private EditText person;//联系人
    private EditText phone;//手机号
    private String[] items = {"拍照", "我的相册"};
    // 头像文件、上传头像的名称、本地图片uri
    private File imageFile;
    private Uri imageUri; // 图片路径
    private String saveFileName = "";
    private BmobUtils bmobUtils;
    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constants.ResultCode.SUCCESS:
                    ImageLoaderUtils.initImage(WholeRentDetailsActivity.this,allRental.getPic().getFileUrl(),
                            head,R.drawable.chat_xe_icon2_03);
                    dialog.dismiss();
                    break;
                case Constants.ResultCode.UPLOAD_SUCCESS:
                    dialog.dismiss();
                    ToastUtils.shortToast(WholeRentDetailsActivity.this,"发布成功");
                    BmobUtils.query = false;
                    BmobUtils.queryCount = 0;
                    startActivity(new Intent(WholeRentDetailsActivity.this,MainActivity.class));
                    finish();
                    break;
            }

        }
    };
    private Account loginInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loginInfo = MyApplication.getInstance().readLoginUser();
        setContentView(R.layout.activity_wholerent_details);

        initView();
        initData();
        bind();
    }

    private void bind() {
        rlPayStyle.setOnClickListener(this);
        tvMiaoShuChoose.setOnClickListener(this);
        rlDesc.setOnClickListener(this);
        head.setOnClickListener(this);
        tvPublish.setOnClickListener(this);
    }

    /**
     * 初始化Bmob,设置标题
     */
    private void initData() {
        allRental = new AllRental();
        orderInfo = new OrderInfo();
        bmobUtils = new BmobUtils(this);
        Intent intent = getIntent();
        if (intent != null) {
            String str = intent.getStringExtra("type");
            if (str != null){
                tvTitle.setText(str);
            }
        }
    }

    private void initView() {
        tvMiaoShuChoose = (TextView) findViewById(R.id.tv_miaoshu_choose);
        rlPayStyle = (RelativeLayout) findViewById(R.id.rl_pay_sytle);
        rlDesc = (RelativeLayout) findViewById(R.id.rl_desc);
        head = (CircleImageView) findViewById(R.id.civ_header);
        tvTitle = (TextView) findViewById(R.id.top_tv_title);
        tvPay = (TextView) findViewById(R.id.tv_pay_fix);
        xiaoqu = (EditText) findViewById(R.id.et_xiaoqu1);
        address = (EditText) findViewById(R.id.ed_quyu);
        shi = (EditText) findViewById(R.id.et_huxing_shi);
        ting = (EditText) findViewById(R.id.et_huxing_ting);
        wei = (EditText) findViewById(R.id.et_huxing_wei);
        mianji = (EditText) findViewById(R.id.et_ceng);
        price = (EditText) findViewById(R.id.et_yuan);
        biaoti = (EditText) findViewById(R.id.et_biaoti);
        person = (EditText) findViewById(R.id.et_lianxiren);
        phone = (EditText) findViewById(R.id.et_shoujihao);
        tvPublish = (TextView) findViewById(R.id.bt_publish);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.rl_pay_sytle:
                Intent intent1 = new Intent(WholeRentDetailsActivity.this,PayStyleActivity.class);
                intent1.putExtra("type","zhengzhu");
                startActivityForResult(intent1,400);
                break;
            case R.id.rl_desc:
            case R.id.tv_miaoshu:
                Intent intent = new Intent(WholeRentDetailsActivity.this,MoreDescActivity.class);
                startActivityForResult(intent,200);
                break;
            case R.id.civ_header:
                showActionSheetDialog(items);
                break;
            case R.id.bt_publish:
                publishRental();
                break;

        }
    }

    /**
     * 发布租房信息
     */
    private void publishRental() {
       if (check()){

           allRental.setId(loginInfo.getId());
           allRental.setAddress(address.getText().toString());
           allRental.setMianji(mianji.getText().toString());
           allRental.setVillage(xiaoqu.getText().toString());
           allRental.setShi(shi.getText().toString());
           allRental.setTing(ting.getText().toString());
           allRental.setWei(wei.getText().toString());
           allRental.setPayStyle(tvPay.getText().toString());
           allRental.setDesc(tvMiaoShuChoose.getText().toString());
           allRental.setTitle(biaoti.getText().toString());
           allRental.setPerson(person.getText().toString());
           allRental.setPhone(phone.getText().toString());
           allRental.setPrice(price.getText().toString());


           orderInfo.setId(loginInfo.getId());
           orderInfo.setTitle(biaoti.getText().toString());
           orderInfo.setCity(address.getText().toString());
           orderInfo.setRent_money(price.getText().toString());
           orderInfo.setType("0");

//           BmobFile bmobFile = new BmobFile(imageFile);
//           bmobUtils.upPublishFile(bmobFile);//这里上传整租图片
           dialog = ProgressDialog.show(this, null, "正在发布...");
           bmobUtils.upLoadAllRental(allRental,orderInfo);
       }else {
           ToastUtils.shortToast(this,"请填写完整信息哦~~~");
       }
    }

    /**
     * 检查填写信息的完整性
     */
    public boolean check(){
//        Log.e("image",imageFile+"");
//        Log.e("xiaoqu",xiaoqu.getText().toString()+"");
//        Log.e("address",address.getText().toString()+"");
//        Log.e("shi",shi.getText().toString()+"");
//        Log.e("ting",ting.getText().toString()+"");
//        Log.e("wei",wei.getText().toString()+"");
//        Log.e("mianji",mianji.getText().toString()+"");
//        Log.e("price",price.getText().toString()+"");
//        Log.e("biaoti",biaoti.getText().toString()+"");
//        Log.e("tvMiaoShuChoose",tvMiaoShuChoose.getText().toString()+"");
//        Log.e("person",person.getText().toString()+"");
//        Log.e("phone",phone.getText().toString()+"");
        if (imageFile == null||xiaoqu.getText().toString().equals("")
                ||address.getText().toString().equals("")||shi.getText().toString().equals("")
                ||ting.getText().toString().equals("")||wei.getText().toString().equals("")
                ||mianji.getText().toString().equals("")||price.getText().toString().equals("")
                ||biaoti.getText().toString().equals("")||tvMiaoShuChoose.getText().toString().equals("")
                ||person.getText().toString().equals("")||phone.getText().toString().equals("")){
            return false;
        }else {
            return true  ;
        }

    }

    //头像选择对话框
    private void showActionSheetDialog(String[] items) {
        ActionSheet actionSheet = new ActionSheet(this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (int i = 0; i < items.length; i++) {
            actionSheet.addSheetItem(items[i], ActionSheet.SheetItemColor.Blue, WholeRentDetailsActivity.this);
        }
        actionSheet.show();

    }

    @Override
    public void onClick(int which) {
        switch (which) {
            case TAKE_PHOTO:
                //拍照
                imageFile = ImageUploadUtil.createImageFile(ImageUploadUtil.CAMERA_SAVEDIR2, ImageUploadUtil.createImageName());
                startActivityForResult(ImageUploadUtil.intentImageCapture(imageFile), ImageUploadUtil.TAKE_PHOTO);
                break;
            case CHOOSE_PHOTO:
                //从相册选择
                startActivityForResult(ImageUtil.intentChooseImg(),
                        CHOOSE_PHOTO);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode){
            case 200:
                if (data == null){
                    tvMiaoShuChoose.setHint("房源描述");
                }else {
                    String str = data.getStringExtra("desc");
                    tvMiaoShuChoose.setText(str);
                }

                break;
            case 400:
                if (data != null){
                    String str1 = data.getStringExtra("payStyle");
                    tvPay.setText(str1);
                }

                break;
            case TAKE_PHOTO:
                if (resultCode == 0) {
                    return;
                }
                //拍照
                ImageUtil.paizhaocreateImagefile(this, imageFile);
                if (imageFile == null) {
                    ToastUtils.shortToast(this, "图片太大无法上传");
                    return;
                }
                doSendThread();//上传图片
                break;
            case CHOOSE_PHOTO:
                //相册
                if (resultCode == 0) return;
                imageUri = data.getData();
                imageFile = MyApplication.getInstance().createimagefile(imageUri, getVmWidth(), getVmHeight());
                if (imageFile == null) {
                    ToastUtils.shortToast(this, "imageFile为空2");
                    return;
                }
                doSendThread();//上传图片
                break;
        }
    }

    /**
     * 上传图片
     */
    private void doSendThread() {
        dialog = ProgressDialog.show(this, null, "正在上传照片...");
        Log.e("image",imageFile.getPath()+"");
        BmobFile bmobFile = new BmobFile(imageFile);
        bmobUtils.upPublishFile(bmobFile);//这里上传整租图片
//        Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath());
//        head.setImageBitmap(bitmap);
    }
}
